import Vue from 'vue'
import Vuex from 'vuex'
import auth from './auth'
import types from './types'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    auth,
    types
  },
  state: {
    initPromise: null,
    initCallbacks: [],
    initOver: false
  },
  getters: {
    initOver: state => state.initOver
  },
  mutations: {
    pushInitCallbask(state, callback) {
      state.initCallbacks.push(callback)
    },
    setInitPromise(state, promise) {
      state.initPromise = promise
    },
    setInitOver(state) {
      state.initOver = true
    }
  },
  actions: {
    initialize({ commit, dispatch }) {
      const promise = new Promise((reslove, reject) => {
        Promise.all([
          dispatch('auth/fetchPublicKey'),
          dispatch('auth/fetchUserInfo'),
          dispatch('types/fetchTypes'),
        ]).then(() => {
          commit('setInitOver')
          commit('setInitPromise', promise)
          reslove()
        }).catch(reject)
      })
    },

    doAfterInit({ state, commit }, callback) {
      if (state.initPromise == null) {
        commit('pushInitCallbask', callback)
      } else {
        state.initPromise.then(callback)
      }
    }
  }
})
